package com.blackline.auto.CIM;

import static org.junit.Assert.fail;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.ui.Select;

import com.blackline.auto.common.CommonMethods;
import com.blackline.declareUI.UI;
import com.blackline.parameters.Parameters;
import com.blackline.parameters.TestData;
/**
 * @author XBO
 * @version Feb, 2013
 * <p>The smoke test to CIM module.
 */
public class CIM_smoketest {
	private WebDriver driver;
	private StringBuffer verificationErrors = new StringBuffer();
	private static Logger logger=Logger.getLogger(CIM_smoketest.class);
	UI UI=new UI();
	Parameters parameters;
	@Before
	public void setUp() throws Exception {
		FirefoxProfile profile=new FirefoxProfile();
		profile.setEnableNativeEvents(true);
		parameters=new Parameters("parameters.xml");

		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		UI.declareAllUI(driver);
	}
	@SuppressWarnings("static-access")
	@Test
	public void CIMsmoketest() throws InterruptedException{
	TestData testdata=new TestData("TestData/CIM_smoketest.xml");
		
		//Generate current time string, and write into Account.Import.txt later
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd-kk-mm-ss");
		Date date = new Date();
		Thread.sleep(5000);
		Date datec=new Date();
		
		String dateString = sdf.format(date);
		String dateStringc=sdf.format(datec);
		logger.info("Current time 1 is: " + dateString);
		logger.info("Current time 2 is: " + dateStringc);
		String inputText = "4000	"+ dateString +"									z2013022001	"+dateStringc+"	A	Asset	TRUE	TRUE	USD	USD	1/31/2011			30000";
		logger.info("The inputText for " + testdata.getInput("accountFile") + " is: " + inputText);
		//Create Account.Import.text file and write inputText into it.
		CommonMethods cm = new CommonMethods();
		cm.createFile(("TestData\\" + testdata.getInput("accountFile")), inputText);
		
		//The absolute path of the Account.CIM.Auto01.txt file.
		String accountFilePath = System.getProperty("user.dir") + "\\TestData\\" + testdata.getInput("accountFile");
		logger.info("Location of " + testdata.getInput("accountFile") + " is: " + accountFilePath);
		
		//Account file without extension: CIM.Import.Auto01.txt > CIM.Import.Auto01
		String inputFileNoExtension = testdata.getInput("accountFile").substring(0, testdata.getInput("accountFile").length()-4);
		logger.info("Account file without extension is: " + inputFileNoExtension);
		
		//Log into system
		UI.LogonPage.Login(driver, parameters.urlDev2, parameters.getLogonID("admin"), parameters.getPassword("admin"));
		UI.NavigationMenu.IMPORTS.click();
		UI.NavigationMenu.Import_Data.click();
		Thread.sleep(5000);
		verificationErrors.append(UI.page.VerifyPageTitle(driver, "Import Data from a file"));
		UI.page.selectOptionForDropdownList(UI.ImportData.Import_dropDownList, "Accounts");
		UI.ImportData.Document_textField.sendKeys(accountFilePath);
		UI.ImportData.Import_button.click();
		if (UI.ImportData.OperationResult.getText().contains("Succeed"))
		{
			logger.info("[Pass!] The importing file operation succeeded!");
		}
		else
		{
			logger.error("[Fail!] The importing file operation failed!");
		}
		UI.NavigationMenu.REPORTS.click();
		UI.NavigationMenu.IMPORTS.click();
		UI.NavigationMenu.Import_Status.click();
		UI.ImportStatus.Process_Name_filterField.sendKeys(inputFileNoExtension);
		UI.ImportStatus.Process_Name_filterField.sendKeys(Keys.ENTER);
		Thread.sleep(20000);
		UI.ImportStatus.Refresh_button.click();
		String Status1 = UI.ImportStatus.Status_of1stSearchedResult.getText();
		String Successful1 = UI.ImportStatus.Successful_of1stSearchedResult.getText();
		String Status2 = UI.ImportStatus.Status_of2ndSearchedResult.getText();
		String Successful2 = UI.ImportStatus.Successful_of2ndSearchedResult.getText();
		String Status3 = UI.ImportStatus.Status_of3rdSearchedResult.getText();
		String Successful3 = UI.ImportStatus.Successful_of3rdSearchedResult.getText();
		
		//System need sometime to complete the status update. So sleep 30 seconds.
		Thread.sleep(30000);
		
		logger.info("Status of item 1 is: " + Status1 + ", and Success of item 1 is: " + Successful1);
		logger.info("Status of item 2 is: " + Status2 + ", and Success of item 2 is: " + Successful2);
		logger.info("Status of item 3 is: " + Status3 + ", and Success of item 3 is: " + Successful3);

		if (Status1.equals("Finished") && Successful1.equals("Yes") && Status2.equals("Finished") && Successful2.equals("Yes") && Status3.equals("Finished") && Successful3.equals("Yes"))
		{
			logger.info("Status of first 3 records are 'Finished' and successfully fields are 'yes'");
		}
		else
		{
			logger.info("[Failed!] At least one status or successful is worng.");
			verificationErrors.append("[Failed!] At least one status or successful is worng.");
		}
		UI.NavigationMenu.ACCOUNTS.click();
		UI.NavigationMenu.View_Reconciliations.click();
		//UI.SessionMenu.DownArrow_Periods.click();
		//UI.SessionMenu.selectDate(driver, "131 2012").click();
		UI.NavigationMenu.REPORTS.click();
		UI.NavigationMenu.ACCOUNTS.click();
		UI.NavigationMenu.View_Reconciliations.click();
		Thread.sleep(15000);
		UI.Accounts_viewReconciliations.Account_textField.sendKeys(dateString);
		UI.Accounts_viewReconciliations.Refresh_icon.click();
		Thread.sleep(15000);
		if (UI.Accounts_viewReconciliations.View.getText().equals("View"))
		{
			logger.info("Account '" + dateString + "' exists.");
		}
		else{
			verificationErrors.append("Can NOT find account: " + dateString);
		}
		//Verify account id anf GL Balance
		UI.SessionMenu.LogOut.click();
		
		
		//P2
		UI.LogonPage.Login(driver, parameters.urlDev2, parameters.getLogonID("admin"), parameters.getPassword("admin"));
		//Generate current time string, and write into Account.Import.txt later

		String inputText2 = "4000	"+ dateStringc +"									z2013022001	z2013022001	C	Asset	TRUE	TRUE	USD	USD	1/31/2011			5000";
		logger.info("The inputText for " + testdata.getInput("accountFile2") + " is: " + inputText2);
		//Create Account.Import.text file and write inputText into it.
		CommonMethods cm2 = new CommonMethods();
		cm2.createFile(("TestData\\" + testdata.getInput("accountFile2")), inputText2);
				
		//The absolute path of the Account.CIM.Auto01.txt file.
		String accountFilePath2 = System.getProperty("user.dir") + "\\TestData\\" + testdata.getInput("accountFile2");
		logger.info("Location of " + testdata.getInput("accountFile2") + " is: " + accountFilePath2);
				
		//Account file without extension: CIM.Import.Auto01.txt > CIM.Import.Auto01
		String inputFileNoExtension2 = testdata.getInput("accountFile2").substring(0, testdata.getInput("accountFile2").length()-4);
		logger.info("Account file without extension is: " + inputFileNoExtension2);
		
		UI.NavigationMenu.REPORTS.click();
		UI.NavigationMenu.IMPORTS.click();
		UI.NavigationMenu.Import_Data.click();
		//verificationErrors.append(UI.page.VerifyPageTitle(driver, "Import Data from a file"));
		UI.page.selectOptionForDropdownList(UI.ImportData.Import_dropDownList, "Accounts");
		UI.ImportData.Document_textField.sendKeys(accountFilePath2);
		UI.ImportData.Import_button.click();
		UI.NavigationMenu.REPORTS.click();
		UI.NavigationMenu.IMPORTS.click();
		UI.NavigationMenu.Import_Status.click();
		UI.ImportStatus.Process_Name_filterField.sendKeys(inputFileNoExtension2);
		UI.ImportStatus.Apply.click();
		Thread.sleep(20000);
		UI.ImportStatus.Refresh_button.click();
		//Verify import status
		 Status1 = UI.ImportStatus.Status_of1stSearchedResult.getText();
		 Successful1 = UI.ImportStatus.Successful_of1stSearchedResult.getText();
		 Status2 = UI.ImportStatus.Status_of2ndSearchedResult.getText();
		 Successful2 = UI.ImportStatus.Successful_of2ndSearchedResult.getText();
		 Status3 = UI.ImportStatus.Status_of3rdSearchedResult.getText();
		 Successful3 = UI.ImportStatus.Successful_of3rdSearchedResult.getText();
		
		//System need sometime to complete the status update. So sleep 30 seconds.
		Thread.sleep(30000);
		
		logger.info("Status of item 1 is: " + Status1 + ", and Success of item 1 is: " + Successful1);
		logger.info("Status of item 2 is: " + Status2 + ", and Success of item 2 is: " + Successful2);
		logger.info("Status of item 3 is: " + Status3 + ", and Success of item 3 is: " + Successful3);

		if (Status1.equals("Finished") && Successful1.equals("Yes") && Status2.equals("Finished") && Successful2.equals("Yes") && Status3.equals("Finished") && Successful3.equals("Yes"))
		{
			logger.info("Status of first 3 records are 'Finished' and successfully fields are 'yes'");
		}
		else
		{
			logger.info("[Failed!] At least one status or successful is worng.");
			verificationErrors.append("[Failed!] At least one status or successful is worng.");
		}
		

		UI.NavigationMenu.REPORTS.click();
		UI.NavigationMenu.CIM.click();
		UI.NavigationMenu.View_Reconciliations_CIM.click();
		Thread.sleep(15000);
		UI.ViewReconciliations_CIM.Account_textField.sendKeys(dateStringc);
		UI.ViewReconciliations_CIM.Apply_Link.click();
		Thread.sleep(15000);
		if (UI.ViewReconciliations_CIM.View.getText().equals("View"))
		{
			logger.info("Account '" + dateStringc + "' exists.");
		}
		else{
			verificationErrors.append("Can NOT find account: " + dateStringc);
		}
		//Verify account id and GL Balance
		UI.SessionMenu.LogOut.click();
		//P3
		UI.LogonPage.Login(driver, parameters.urlDev2, parameters.getLogonID("admin"), parameters.getPassword("admin"));
		UI.NavigationMenu.CIM.click();
		UI.NavigationMenu.Consolidation_Accounts.click();
		UI.Consolidations.Account_textField.sendKeys(dateStringc);
		UI.Consolidations.Apply_Link.click();
		//Verify status
		
		UI.Consolidations.Edit_Icon.click();
		Thread.sleep(5000);
		UI.AssignmentPage_CIM.Preparer_textField.sendKeys(parameters.getFullName("preparer"));
		UI.AssignmentPage_CIM.Approver_textField.sendKeys(parameters.getFullName("approver"));
		Thread.sleep(5000);
		UI.AssignmentPage_CIM.Copyright_text.click();
		UI.AssignmentPage_CIM.Reviewer_textField.sendKeys(parameters.getFullName("reviewer"));
		Thread.sleep(5000);
		UI.AssignmentPage_CIM.Copyright_text.click();
		UI.AssignmentPage_CIM.Account_Reviewer_textField.sendKeys(parameters.getFullName("ar"));
		Thread.sleep(5000);
		UI.AssignmentPage_CIM.Copyright_text.click();
		UI.AssignmentPage_CIM.Account_Manager_textField.sendKeys(parameters.getFullName("am"));
		Thread.sleep(5000);
		UI.AssignmentPage_CIM.Copyright_text.click();
		UI.AssignmentPage_CIM.Internal_Auditor_textField.sendKeys(parameters.getFullName("ia"));
		Thread.sleep(5000);
		UI.AssignmentPage_CIM.Copyright_text.click();
		UI.AssignmentPage_CIM.Save_button.click();
		
		UI.Consolidations.Account_textField.sendKeys(dateStringc);
		UI.Consolidations.Account_textField.sendKeys(Keys.ENTER);
		//Check the preparer of searched result
		
		UI.SessionMenu.LogOut.click();
		//P4
		//UI.LogonPage.Login(driver, parameters.urlDev2, parameters.getLogonID("preparer"), parameters.getPassword("preparer"));
		UI.LogonPage.LoginID.clear();
	    UI.LogonPage.LoginID.sendKeys(parameters.getLogonID("preparer"));
	    logger.info("User: " + parameters.getLogonID("preparer"));
	    UI.LogonPage.Password.clear();
	    UI.LogonPage.Password.sendKeys(parameters.getPassword("preparer"));
	    logger.info("Password is typed in.");
	    UI.LogonPage.LoginButton.click();
	    logger.info("Clicked Login button");
	    verificationErrors.append(UI.LogonPage.VerifyLogon(parameters.getLogonID("preparer"), driver));
		
		UI.NavigationMenu.CIM.click();
		UI.Consolidation_Accounts.Account_textField.sendKeys(dateStringc);
		UI.Consolidation_Accounts.Apply_Link.click();
		//verify BL
		UI.Consolidation_Accounts.Edit_Icon.click();
		UI.Reconciliation_CIM.Add_Supporting_Item_link.click();
		verificationErrors.append(UI.page.VerifyPageTitle(driver, "Add Item"));
		UI.AddItem_CIM.Amount_textField.sendKeys(testdata.getInput("addItemAmount"));
		UI.AddItem_CIM.List_Component_radioButton.click();
		
		
		UI.AddItem_CIM.Save_button.click();
		//Verify
		if (UI.Reconciliation_CIM.Certify_button.isEnabled())
		{
			logger.info("Certify button is enabled.");
			UI.Reconciliation_CIM.Certify_button.click();
		}
		else
		{
			verificationErrors.append("Certify button is NOT enabled.");
		}
		
		
		UI.Consolidation_Accounts.Account_textField.clear();
		UI.Consolidation_Accounts.Account_textField.sendKeys(dateStringc); 
		if ("View".equals(UI.Consolidation_Accounts.View_linkOf1stSearchedResult.getText()))
		{
			logger.info("[Pass!] The status is : View, not 'Edit' anymore.");
		}
		else
		{
			verificationErrors.append("[Fail!] The status should be 'View', but not.");
		}
		
		//Verify the symbol shows.
		if(UI.Consolidation_Accounts.CertStatus_icon != null)
		{
			logger.info("[Pass!] CertStatus icon exists.");
		}
		else
		{
			verificationErrors.append("[Fail!] CertStatus icon does NOT exists.");
		}
		
		UI.SessionMenu.LogOut.click();
		
		//P5
		UI.LogonPage.Login(driver, parameters.urlDev2, parameters.getLogonID("approver"), parameters.getPassword("approver"));
		UI.NavigationMenu.CIM.click();
		UI.Consolidation_Accounts.Account_textField.sendKeys(dateStringc);
		//UI.Consolidation_Accounts.Account_textField.sendKeys("20130301-16-05-21");
		UI.Consolidation_Accounts.Apply_Link.click();
		Thread.sleep(5000);
		UI.Consolidation_Accounts.Cert_Icon.click();
		Thread.sleep(5000);
		UI.Reconciliation_CIM.Reject_button.click();
		Thread.sleep(5000);
		String currentWindow = driver.getWindowHandle();
		
		try{
        new Select(UI.Reconciliation_CIM.Reason_Code_DropdownList).selectByIndex(4);
        UI.Reconciliation_CIM.Continue_Button.click();
		}catch(NoSuchElementException e){
			logger.info("Not find Reason Code DropdownList");
		}
        Thread.sleep(5000);
        driver.switchTo().frame("Consolidation");
        Thread.sleep(5000);
        UI.SendNotificationofRejection.Send_Button.click();
        Thread.sleep(5000);
        driver.switchTo().window(currentWindow);//Back to previous window.
        logger.info("Title of current window: "+driver.getWindowHandle() + driver.getTitle()+", URL is: " + driver.getCurrentUrl());
        Thread.sleep(5000);
        UI.Consolidation_Accounts.Account_textField.clear();
		UI.Consolidation_Accounts.Account_textField.sendKeys(dateStringc);
		//UI.Consolidation_Accounts.Account_textField.sendKeys("20130301-16-05-21");
		UI.Consolidation_Accounts.Apply_Link.click();
		
		//Check 'Rej' status
		if (UI.Consolidation_Accounts.Rej_icon.getText().equals("Rej"))
		{
			logger.info("[Pass!] Status is 'Rej'");
		}
		else
		{
			verificationErrors.append("[Fail!] Status is NOT 'Rej'");
		}
        
        UI.SessionMenu.LogOut.click();
		logger.info("Clicked 'Logout'");
	}
	@After
	public void tearDown() throws Exception {
		CommonMethods.takeScreenShot(this.getClass(), driver);
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}
}
